<template>
    <div class="login">
        <div class="title">GoEasy IM</div>
        <input type="text" class="input-box" v-model="username" placeholder="请输入账号">
        <input type="password" class="input-box" v-model="password" placeholder="请输入密码">
        <div class="alert-box" v-show="showError">
            <span>请输入正确的用户名和密码</span>
        </div>
        <button class="login-btn" @click="login">登录</button>
    </div>
</template>

<script>
    export default {
        name: "Login",
        data() {
            return {
                username: '',
                password: '',
                showError: false
            }
        },

        methods: {
            login() {//登录
                if (this.username.trim() != "" && this.password.trim() != "") {
                    this.imService.initData();
                    let loginResult = this.imService.login(this.username, this.password);
                    if (loginResult) {
                        //连接IM
                        this.imService.connectIM();
                        this.subscribeGroupMessage();
                        this.$router.push({name: 'index'});
                    } else {
                        this.showError = true;
                        console.log('登录失败')
                    }
                    return;
                }
                this.showError = true;
            },
            subscribeGroupMessage () {
                let groups = this.imService.groups;
                let groupIds = Object.keys(groups);
                this.im.subscribeGroup(groupIds)
                    .then(() => {
                        console.log('订阅群消息成功')
                    })
                    .catch(error => {
                        console.log('订阅群消息失败')
                        console.log(error)
                    })
            }
        }
    }
</script>

<style scoped>
    @import "./login.css";
</style>